#include "stdafx.h"
#include "timeFunc.h"
#include <time.h>
#include <ctime>
#include <chrono>

std::string Tool_GetCurrentTimeToString()
{
	std::time_t rawtime;
	struct tm * timeinfo;
	char buffer[256];

	std::time(&rawtime);								//get the current time
	timeinfo = std::localtime(&rawtime);		//convert time_t to struct*tm

	strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S.", timeinfo);		//format time to string

	return std::string(buffer);
}

unsigned long long Tool_ConvertToTimet(int iYear, int iMonth, int iDay, int iHour, int iMin, int iSecond, int iMsecond)
{
	struct tm mytm;
	mytm.tm_year = iYear - 1900;
	mytm.tm_mon = iMonth - 1;
	mytm.tm_mday = iDay;
	mytm.tm_hour = iHour;
	mytm.tm_min = iMin;
	mytm.tm_sec = iSecond;

	time_t curTime = mktime(&mytm);

	unsigned long long  dw64Time = curTime;
	dw64Time = dw64Time * 1000 + iMsecond;

	return dw64Time;
}

long long Tool_GetTickCount()
{
	using namespace std::chrono;

	system_clock::time_point now = system_clock::now();

	auto duration = now.time_since_epoch();
	long long  iMillisecond = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();

	return iMillisecond;
}

int64_t Tool_GetTimeSecond()
{
	using namespace std::chrono;

	system_clock::time_point now = system_clock::now();

	auto duration = now.time_since_epoch();
	int64_t iSecond = std::chrono::duration_cast<std::chrono::seconds>(duration).count();

	return iSecond;
}

void Tool_getDateTimeWithMillisecond(DateTimeWithMilsec& timeStruct)
{
	auto now = std::chrono::system_clock::now();
	time_t in_time_t = std::chrono::system_clock::to_time_t(now);
	struct tm* ptmNow = localtime(&in_time_t);

	auto duration = now.time_since_epoch();
	long long  iMillisecond = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();

	timeStruct.year = ptmNow->tm_year + 1900;
	timeStruct.month = ptmNow->tm_mon + 1;
	timeStruct.day = ptmNow->tm_mday;
	timeStruct.hour = ptmNow->tm_hour;
	timeStruct.minute = ptmNow->tm_min;
	timeStruct.second = ptmNow->tm_sec;
	timeStruct.millisecond = static_cast<int>(iMillisecond % 1000);
}

tm Tool_TimeNowTm()
{
	time_t now = std::time(0);
	return *std::localtime(&now);
}

std::string Tool_getTimeString()
{
	DateTimeWithMilsec timeStruct;
	Tool_getDateTimeWithMillisecond(timeStruct);

	char chTime[64] = { 0 };
	sprintf(chTime, "%04d%02d%02d%02d%02d%02d%03d",
		timeStruct.year,
		timeStruct.month,
		timeStruct.day,
		timeStruct.hour,
		timeStruct.minute,
		timeStruct.second,
		timeStruct.millisecond);

	return std::string(chTime);
}